package com.hd123.rumba.gwt.widget.client;

import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class NumberBox extends TextBox implements KeyboardListener {

  public NumberBox() {
    super();
    addKeyboardListener(this);
  }

  public void onKeyDown(Widget sender, char keyCode, int modifiers) {

  }

  public void onKeyPress(Widget sender, char keyCode, int modifiers) {
    if (Util.isNavKey(keyCode))
      return;
    String s = ((NumberBox) sender).getText();
    Character c = new Character(keyCode);
    if ("".equals(s) && (keyCode == '+' || keyCode == '-'))
      return;
    int i = getCursorPos();
    s = s.substring(0, i) + c + s.substring(i);
    if (!isNumber(s))
      cancelKey();
  }

  public void onKeyUp(Widget sender, char keyCode, int modifiers) {
  }

  public boolean isNumber(String s) {
    try {
      Double.parseDouble(s);
      return true;
    } catch (Exception e) {
      return false;
    }
  }

}
